package com.loma.common.utils.ext

import android.util.Log
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.loma.common.BuildConfig
import com.loma.common.utils.util.LoggerPrinter
import com.tencent.mmkv.MMKV
import org.json.JSONObject


/**
 * Created by loma on 2018/1/31.
 */
fun Any.log(  )   {
    if ( BuildConfig.DEBUG){
        var  t=  "zjt"
        apply {
            val s = getMethodNames1()

            if ( toString().contains("\n")) {
                Log.e(t, String.format(s, toString().replace("\n".toRegex(), "\n  ")))
            } else {
                Log.e(t, String.format(s, toString()))
            }
        }


    }

}


infix fun Any.log(   tag: String? )   {
    if ( BuildConfig.DEBUG){
        var  t=tag?:"zjt"
        apply {
            val s = getMethodNames1()

            if ( toString().contains("\n")) {
                Log.e(t, String.format(s, toString().replace("\n".toRegex(), "\n  ")))
            } else {
                Log.e(t, String.format(s, toString()))
            }
        }


    }

}



inline fun getMethodNames1(): String {
    val sElements = Thread.currentThread().stackTrace

    var stackOffset = LoggerPrinter.getStackOffset(sElements)

    stackOffset++
    val builder = StringBuilder()
    builder.append(LoggerPrinter.BR)
    builder.append(LoggerPrinter.NULL_DIVIDER)
    builder.append(LoggerPrinter.BR)
    builder.append(LoggerPrinter.TOP_BORDER)
        .append(LoggerPrinter.BR)

    // 添加当前线程名
    builder.append("  " + "Thread: " + Thread.currentThread().name).append(LoggerPrinter.BR)
        .append(LoggerPrinter.MIDDLE_BORDER).append(LoggerPrinter.BR)
        // 添加类名、方法名、行数
        .append("  ")
        .append(sElements[stackOffset].className)
        .append(".")
        .append(sElements[stackOffset].methodName)
        .append(" ")
        .append(" (")
        .append(sElements[stackOffset].fileName)
        .append(":")
        .append(sElements[stackOffset].lineNumber)
        .append(")")
        .append(LoggerPrinter.BR)
        .append(LoggerPrinter.MIDDLE_BORDER).append(LoggerPrinter.BR)
        // 添加打印的日志信息
        .append("  ").append("%s").append(LoggerPrinter.BR)
        .append(LoggerPrinter.BOTTOM_BORDER).append(LoggerPrinter.BR)

    return builder.toString()
}



fun Any.toJsonString(): String {

    if (this is JSONObject) {
        return this.toString()
    }
    return Gson().toJson(this)

}

inline fun <reified T : Any> String.getObject(): T {
    this.log()
    return GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create()
        .fromJson<T>(this, T::class.java)


}

fun Any.saveToMMKV(key: String): Any {

    MMKV.defaultMMKV().encode(key, this.toString())

    return this

}



